<!-- excel数据导入 导出 -->
<template>
    <div class="pages">
        <div class="head">
            <el-upload class="upload-demo" ref="upload" action="" :auto-upload="false" accept=""
                :on-change="analysisExcel" multiple :show-file-list="false">
                <el-button type="primary" :icon="UploadFilled">导入文件列表</el-button>
            </el-upload>
            <el-button type="primary" :icon="Download" @click="downClick">导出</el-button>
        </div>
        <div>
            <el-table :data="tableData" style="width: 100%">
                <el-table-column prop="index" label="序号" width="180" />
                <el-table-column prop="username" label="用户名" width="180" />
                <el-table-column prop="status" label="状态" />
                <el-table-column prop="createTime" label="创建时间" />
            </el-table>
        </div>
    </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import * as XLSX from 'xlsx'
import { UploadFilled, Download } from '@element-plus/icons-vue'

const loading = ref(false)
const tableData = ref([])

const analysisExcel = (file) => {
    loading.value = true
    console.log(file)

    // 只能上传一个Excel，重复上传会覆盖之前的
    file = file.raw
    const reader = new FileReader()
    reader.readAsArrayBuffer(file)
    reader.onload = function () {
        const buffer = reader.result

        const bytes = new Uint8Array(buffer)
        const length = bytes.byteLength
        let binary = ""
        for (let i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i])
        }
        const wb = XLSX.read(binary, {
            type: "binary"
        })
        const outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
        console.log(outdata)
        let da = [...outdata]
        // 这里是把表格里面的名称改成表格里面的字段
        da = da.map((item) => {
            const newItem = {
                index: Number(item["序号"]), // 序号
                username: item["用户名"], // 用户名
                status: item["状态"], // 状态
                createTime: item["创建时间"] // 创建时间

            }
            return newItem
        })
        console.log(da)

        tableData.value = da
        loading.value = false
    }
}

const downClick = () => {
    if (!tableData.value.length) return ElMessage.warning('请先导入数据再导出！');

    const newList = tableData.value.map((item) => {
        return {
            "序号": item.index,
            "用户名": item.username,
            "状态": item.status,
            "创建时间": item.createTime
        }
    })
    const ws = XLSX.utils.json_to_sheet(newList, { origin: 'A1' });
    const wb = { Sheets: { 'data': ws }, SheetNames: ['data'] }
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
    const blob = new Blob([excelBuffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8" })
    const blobUrl = URL.createObjectURL(blob)
    const a = document.createElement('a');
    a.href = blobUrl;
    a.download = '导出数据' + new Date().getTime() + '.xlsx';
    a.click();
    URL.revokeObjectURL(blobUrl);
    nextTick(() => {
        loading.value = false
    })
}




</script>

<style lang="scss" scoped>
.pages {
    padding: 0;

    .head {
        display: flex;
        align-items: center;

        button {
            margin-right: 10px;
        }
    }
}
</style>